﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace testComPort
{
    using System.Security.AccessControl;

    using SerialPortListener;

    public partial class Form1 : Form
    {
        // Add this variable

        SerialPortHelper _helper = new SerialPortHelper();


        string RxString;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            
                //var flag = false;
                //int i = 1;
                //while (!flag && i < 20)
                //{
                //    try
                //    {
                //        serialPort1.Close();
                //        System.Threading.Thread.Sleep(500);
                //        serialPort1.PortName = "COM" + i.ToString();
                //        labelPort.Text = "Traying Opening Port" + serialPort1.PortName;
                //        serialPort1.BaudRate = 9600;
                //        i++;
                //        serialPort1.Open();
                //        if (serialPort1.IsOpen)
                //        {
                //            flag = Comprobar18();
                //        }
                //    }
                //    catch (System.IO.IOException exception)
                //    {
                //        labelPort.Text = exception.Message;
                //    }
                //}

            _helper.Lectura += new System.EventHandler(this.LecturaDelPuerto);
            labelPort.Text = _helper.DetectModule();// "Port Detected: " + serialPort1.PortName + " BaudRate: " + serialPort1.BaudRate + "Por Open: " + serialPort1.IsOpen;
            
                buttonStart.Enabled = false;
                buttonStop.Enabled = true;
                textBox1.ReadOnly = false;
           
            
        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.AppendText(text);
            }
        }

        private void LecturaDelPuerto(object sender, EventArgs e)
        {
            var txt = _helper.ReadExisting();
            SetText(txt);
        }



        private void buttonStop_Click(object sender, EventArgs e)
        {
            labelPort.Text = "Port is Closed";
            if (_helper.ClosePort())
            {
                buttonStart.Enabled = true;
                buttonStop.Enabled = false;
                textBox1.ReadOnly = true;
            }

            buttonStart.Enabled = true;

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (serialPort1.IsOpen) serialPort1.Close();
            _helper.ClosePort();
        }

       
       
       


        /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            // If the port is closed, don't try to send a character.

            //if (!serialPort1.IsOpen) return;

            //// Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
            //byte[] data = HexStringToByteArray(textBox1.Text);

            //// Send the binary data out the port
            //serialPort1.Write(data, 0, data.Length);
            

            textBox1.Text = "";
        }


        string _lastMessage = String.Empty;

        private void bloop_Click(object sender, EventArgs e)
        {
            
            int direction = 1;
            int cant = (int) numericLoop.Value;

            for (int i = 0; i < cant; i++)
            {
                _lastMessage = CompletarDireccion(direction.ToString("X"));
                byte[] dir = StringToByteArray(_lastMessage);

                Escribir(dir);
                System.Threading.Thread.Sleep(999);
                direction++;

            }
        }


        private void Escribir(byte[] dir)
        {
            byte[] mBuffer = new byte[6];
            mBuffer[0] = dir[0];
            mBuffer[1] = dir[1];
            mBuffer[2] = 0x11;
            mBuffer[3] = 0x22;
            mBuffer[4] = 0x33;
            mBuffer[5] = 0x44;
            //serialPort1.Write(mBuffer, 0, mBuffer.Length);
        }

        private string CompletarDireccion(string str)
        {
            var length = str.Length;
            if ((length % 2) == 0 & length == 4)
            {
                return str;
            }
            return CompletarDireccion("0" + str);
        }

        public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }
    }
}
